﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using Azukit.WPF.Command;
using Azukit.WPF.ViewModel;
using Hibiku.Models;
using Hibiku.Services;

namespace Hibiku.ViewModels
{
    public class FilterEditViewModel : ViewAwareViewModelBase
    {
        public ICommand SaveFiltersCommand
        {
            get;
            private set;
        }

        public ICommand DeleteFilterCommand
        {
            get;
            private set;
        }

        public ICommand AddFilterCommand
        {
            get;
            private set;
        }

        public ObservableCollection<FilterRuleModel> FilterRules
        {
            get;
            private set;
        }

        private readonly IApplicationConfigurationService m_configurationService;
        private readonly IFeatureTrackingService m_featureTrackingService;

        public FilterEditViewModel(IApplicationConfigurationService configurationService,
            IFeatureTrackingService featureTrackingService)
        {
            m_configurationService = configurationService;
            m_featureTrackingService = featureTrackingService;

            FilterRules = new ObservableCollection<FilterRuleModel>(m_configurationService.Configuration.FilterRules.OrderBy(x => x.Action));

            SaveFiltersCommand = new DelegatingCommand(DoSaveFilters);
            AddFilterCommand = new DelegatingCommand(DoAddFilter);
            DeleteFilterCommand = new DelegatingCommand(DoDeleteFilter);
        }

        private void DoSaveFilters(object ignore)
        {
            m_featureTrackingService.TrackFeature("Filters.Save");

            m_configurationService.Configuration.FilterRules = FilterRules;
            m_configurationService.Save();
        }

        public void DoAddFilter(object ignore)
        {
            m_featureTrackingService.TrackFeature("Filters.Add");

            FilterRules.Add(new FilterRuleModel("", EFilterMatchAction.Highlight));
        }

        public void DoDeleteFilter(object param)
        {
            m_featureTrackingService.TrackFeature("Filters.Delete");

            var filter = param as FilterRuleModel;

            if (filter != null)
            {
                FilterRules.Remove(filter);
            }
        }
    }
}
